package com.hmz.backend.service.Impl.friend;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmz.backend.entity.ChatRoom;
import com.hmz.backend.entity.Friend;
import com.hmz.backend.entity.User;
import com.hmz.backend.mapper.ChatRoomMapper;
import com.hmz.backend.mapper.FriendMapper;
import com.hmz.backend.mapper.UserMapper;
import com.hmz.backend.service.friend.AddFriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AddFriendServiceImpl implements AddFriendService {
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private ChatRoomMapper chatRoomMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public JSONObject addFriend(JSONObject data) {
        redisTemplate.opsForHash().delete("friendRequest"+data.get("userId"),data.get("friendId").toString());
        Friend friend = new Friend();
        friend.setFriendId((int) data.get("friendId"));
        friend.setUserId((int) data.get("userId"));
        ChatRoom chatRoom = new ChatRoom();
        chatRoom.setTime(new Date());
        chatRoom.setNum(2);
        try {
            //插入好友关系
            int insert = friendMapper.insert(friend);
            //创建好友聊天室
            int insert2 = chatRoomMapper.insert(chatRoom);
            //让两个好友加入聊天室
            chatRoomMapper.joinChatRoom(friend.getUserId(), chatRoom.getId());
            chatRoomMapper.joinChatRoom(friend.getFriendId(), chatRoom.getId());
            //创建表
            chatRoomMapper.createMessageTable(chatRoom.getId());
            return new JSONObject().set("message","添加好友成功！");
        } catch (Exception e) {
            System.out.println(e);
            return new JSONObject().set("message","添加好友失败！");
        }
    }

    @Override
    public JSONObject friendRequest(JSONObject data) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",data.get("userId"));
        User user = userMapper.selectOne(queryWrapper);
        redisTemplate.opsForHash().put("friendRequest"+data.get("friendId"),user.getUserId().toString(),user);
        return new JSONObject().set("message","已发送好友申请");
    }

    @Override
    public JSONObject getFriendRequest(int userId) {
        List<String> list = redisTemplate.opsForHash().values("friendRequest" + userId); //获取userId 下的所有好友申请列表
        return new JSONObject().set("message","获取列表成功").set("list",list);
    }
}
